<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/26 22:41
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Slider_Model extends WX_Model
{
    private $slideNum = 4;

    private $width = 640;
    private $height = 360;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();

        try {
            $config = $this->_getConfigByKey('general', 'value');
            if (!empty($config) && !empty($config['value'])) {
                $config = json_decode($config['value'], true);
                $this->slideNum = !empty($config['slideNum']) ? intval($config['slideNum']) : $this->slideNum;
            }
        } catch(Exception $e){
            throw new Exception('配置错误');
        }
    }

    /**
     * 请求幻灯列表
     */
    public function getSliderLists()
    {
        $db = clone($this->db);
        $q = $db->select('b.id, b.name, b.thumb, b.streamId, b.created')
            ->limit($this->slideNum)
            ->order_by('modified', 'DESC')
            ->order_by('created', 'DESC')
            ->where('status', 1)
            ->from('base as b')
            ->get();
        $rows = $q->result_array();
        $return = array();
        if (!empty($rows)) foreach ($rows as $item) {
            $return[] = array(
                'baseId' => intval($item['id']),
                'baseName' => value($item, 'name'),
                'thumb' => thumb($item['thumb'], $this->width, $this->height),
                'created' => formateTimeStamp($item['created']),
                'isLive' => !empty($item['streamId'])
            );
        } else {
            return [];
        }

        return $return;
    }

    /**
     * 获取配置
     * @param $key
     * @param string $field
     * @return bool
     */
    protected function _getConfigByKey($key, $field = '*')
    {
        if (empty($key)) {
            return false;
        }

        $db = clone($this->db);
        $query = $db->select($field)
            ->from('setting')
            ->where(array('use' => 'mobile', 'key' => $key))
            ->get();
        return $query->row_array();
    }

}
